<template>
  <div class='over'>
    <tree :model='functions' :is-click="false" v-ref:tree @toggle="toggled">
      <span partial :class="{ 'tree-img': isFolder(row), 'tree-span': !isFolder(row) }">
        <img v-if="isFolder(row)" :src="row.data.icon" alt="">{{row.data.name}}
      </span>
    </tree>
  </div>
</template>
<script>
export default {
  props: ['functions', 'userid'],
  title: '左侧树菜单',
  data () {
    return {
      index: -1,
      name: null
    }
  },
  methods: {
    open (row) {
      if (row.data.link) {
        this.$goto(row.data.link, {f: this.functions}, 'main')
      }
    },
    changeSelect(name) {
      if (!name) {
        this.$refs.tree.selectStore.select(null)
        return
      }
      this.name = name
      let index = this.selfFindIndex(name)
      this.index = index
      // 当前激活页签有，index为-1，说明菜单收缩
      this.changeSelected(index)
    },
    selfFindIndex (name) {
      return this.$refs.tree.toNode.findIndex((item) => {
        return item.data.link === name
      })
    },
    changeSelected (index) {
      if (index === -1) {
        this.$refs.tree.selectStore.select(null)
      }else {
        this.$refs.tree.selectStore.select(this.$refs.tree.toNode[index])
      }
    },
    toggled () {
      if (this.name && this.index === -1) {
        let index = this.selfFindIndex(this.name)
        if (index !== -1) {
          this.changeSelected(index)
        }
      }
    }
  },
  events: {
    'select-changed': function (data) {
      // 事件回调内的 `this` 自动绑定到注册它的实例上
      this.open(data.val)
    }
  }
}
</script>
